let fs = require("fs");
let http = require("http");
let url = require("url");

let server = http.createServer((request, response) => {
  let urlObj = url.parse(request.url, true);
  // 响应用户显示登陆页的请求
  if (urlObj.pathname == "/login") {
    let data = fs.readFileSync("./views/login.html");
    response.end(data.toString());
    return;
  }
  // 响应用户显示注册页面的请求
  if (urlObj.pathname == "/register") {
    let data = fs.readFileSync("./views/register.html");
    response.end(data.toString());
    return
  }
  // 响应用户点击注册按钮的请求
  if (urlObj.pathname == "/doregister") {
    // 接收表单中提交的数据
    let { query: { username, password } } = urlObj;
    // console.log( username,password );
    let obj = { username, password };
    // 思路：先读取persons.json, 再将读取的内容转换为数组（ JSON.parse() ）,然后将obj添加到数组中。
    // 再将数组转换为字符串，使用fs.writeFile()写入到persons.json中
    let data = fs.readFileSync("./persons.json");
    let arr = JSON.parse(data.toString());
    arr.push(obj);
    fs.writeFileSync("./persons.json", JSON.stringify(arr));
    response.setHeader("content-type", "text/html;charset=utf8");
    response.end("注册完成")
  }

  // 响应用户点击登录以后的请求
  if (urlObj.pathname == "/dologin") {
    let { query: { username, password } } = urlObj;
    // 思路：先读取persons.json, 再将读取的内容转换为数组,再判断数组中有么有复合条件的对象
    let data = fs.readFileSync("./persons.json");
    let arr = JSON.parse(data.toString());
    //  如果findIndex()找不到满足条件的项，则返回 -1
    let a = arr.findIndex((item) => {
      return item.username == username && item.password == password;
    })
    if (a != -1) {
      response.setHeader("content-type", "text/html;charset=utf8");
      response.end("登录成功");
      return;
    } else {
      response.setHeader("content-type", "text/html;charset=utf8");
      response.end("账号或密码错误");
      return;
    }
  }
})

server.listen(3000, () => {
  console.log("http服务已启动在3000端口");
})